package com.example.windowdemo.callback

import android.content.Context
import android.os.Environment
import com.tencent.mmkv.MMKV

/**
 *@author: njb
 *@date:   2023/8/9 15:14
 *@desc:
 */
class MMKVUtils private constructor(){
    private lateinit var mmKv:MMKV

    companion object{
        val mInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            MMKVUtils()
        }
    }

    fun init(context: Context){
        MMKV.initialize(context,Environment.getExternalStorageDirectory().absolutePath + "/mmkv")
        mmKv = MMKV.mmkvWithID("MyId",MMKV.MULTI_PROCESS_MODE)
    }

    fun encode(key: String, value: Any) {
        when (value) {
            is String -> mmKv.encode(key, value)
            is Int -> mmKv.encode(key, value)
            is Boolean -> mmKv.encode(key, value)
            is Long -> mmKv.encode(key, value)
            is Float -> mmKv.encode(key, value)
            is Double -> mmKv.encode(key, value)
        }
    }

    internal inline fun <reified T> decode(key: String, defaultValue: T): T {
        return when (T::class) {
            String::class -> mmKv.decodeString(key, defaultValue as String?) as T
            Int::class -> mmKv.decodeInt(key, defaultValue as Int) as T
            Boolean::class -> mmKv.decodeBool(key, defaultValue as Boolean) as T
            Long::class -> mmKv.decodeLong(key, defaultValue as Long) as T
            Float::class -> mmKv.decodeFloat(key, defaultValue as Float) as T
            Double::class -> mmKv.decodeDouble(key, defaultValue as Double) as T
            else -> throw IllegalArgumentException("Unsupported type")
        }
    }

}